#!/usr/bin/php5
<?

require_once("./cfg/settings.php");

function http_parse_headers($headers=false)
{
	if($headers === false)
	{
		return false;
	}

	$headers = str_replace("\r","",$headers);
	$headers = explode("\n",$headers);

	foreach($headers as $value)
	{
		$header = explode(": ",$value);
		if($header[0] && !isset($header[1]))
		{
			$headerdata['status'] = $header[0];
		}
		elseif($header[0] && $header[1])
		{
			$headerdata[$header[0]] = $header[1];
		}
	}
	return $headerdata;
}


function get_server_modified()
{
	global $UPDATE_URL;
	$tmp = curl_init($UPDATE_URL);
	curl_setopt($tmp, CURLOPT_NOBODY, true);
	curl_setopt($tmp, CURLOPT_HEADER, true);
	curl_setopt($tmp, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($tmp);
	if($result === false)
	{
		echo "Failed to fetch header\n";
		return(false);
	}

	$header = http_parse_headers($result);
	if($header === false)
	{	
		echo "Failed to parse header\n";
		return(false);
	}

	return($header["Last-Modified"]);
}

function get_current_server_modified()
{
	global $SERVER_DIR;
	if(is_file($SERVER_DIR . "./version"))
		return(file_get_contents($SERVER_DIR . "./version"));
	else
		return(false);
}

function do_update()
{
	if (!function_exists("curl_init"))
	{
		echo "Cannot auto-update the server, failed to find curl support\n";
	}
	global $SERVER_DIR;
	global $UPDATE_URL;
	if(get_server_modified() != get_current_server_modified())
	{
		echo "Getting updated server...\n";
		$tmp = curl_init($UPDATE_URL);
		curl_setopt($tmp, CURLOPT_HEADER, false);
		curl_setopt($tmp, CURLOPT_RETURNTRANSFER, true);
		$result = curl_exec($tmp);
		if($result === false)
		{
			echo "Failed to fetch server\n";
			return(false);
		}

		$pid = posix_getpid();
		if(file_put_contents("/tmp/$pid-server", $result) === false)
		{
			echo "Failed to save file server\n";
			return(false);
		}

		if(rename("/tmp/$pid-server", $SERVER_DIR . "./minecraft_server.jar") === false)
		{
			echo "Failed to move server\n";
			return(false);
		}

		if(file_put_contents($SERVER_DIR . "./version", get_server_modified()) === false)
		{
			echo "Failed to save new server version\n";
		}

		echo "Success\n";

		return(true);
	}
	else
	{
		echo "Server is up to date\n";
	}
}

?>
